package com.weiyuwqj.server.service.user.impl;

import com.github.pagehelper.PageHelper;
import com.weiyuwqj.api.common.PageList;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.constant.Constants;
import com.weiyuwqj.api.constant.OftenUserdNumber;
import com.weiyuwqj.api.exception.CrowdException;
//import com.weiyuwqj.api.hengfeng.PayConstants;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.user.HfUserBindCard;
//import com.weiyuwqj.api.hengfeng.model.user.HfUserPlatformAccount;
import com.weiyuwqj.api.model.BasExperiencedGold;
import com.weiyuwqj.api.model.BasUser;
import com.weiyuwqj.api.model.BasUserInfo;
import com.weiyuwqj.api.model.BasUserInvite;
import com.weiyuwqj.api.model.BasUserSecurity;
import com.weiyuwqj.api.model.BusAccount;
import com.weiyuwqj.api.model.BusAccountBank;
import com.weiyuwqj.api.model.BusIncomeStat;
import com.weiyuwqj.api.model.BusUserIntegral;
import com.weiyuwqj.api.model.BusUserStat;
import com.weiyuwqj.api.model.SysAppSettings;
import com.weiyuwqj.api.model.TicketParamEntity;
import com.weiyuwqj.api.model.vo.BasUserInfoVo;
import com.weiyuwqj.api.model.vo.BusAccountBankVo;
import com.weiyuwqj.api.model.vo.GuaranteeSecurityAndBankVo;
import com.weiyuwqj.api.model.vo.UserInvestVo;
import com.weiyuwqj.api.model.vo.UserVo;
import com.weiyuwqj.api.service.BasUserService;
import com.weiyuwqj.api.service.module.creater.AbstractLogCreater;
import com.weiyuwqj.api.service.module.creater.RegisterLogCreater;
import com.weiyuwqj.api.util.DateUtils;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.MD5;
import com.weiyuwqj.api.util.RadixHelper;
import com.weiyuwqj.api.util.RandomCodesUtils;
import com.weiyuwqj.server.mapper.BasCouponMapper;
import com.weiyuwqj.server.mapper.BasExperiencedGoldMapper;
import com.weiyuwqj.server.mapper.BasTicketMapper;
import com.weiyuwqj.server.mapper.BasUserInfoMapper;
import com.weiyuwqj.server.mapper.BasUserInviteMapper;
import com.weiyuwqj.server.mapper.BasUserMapper;
import com.weiyuwqj.server.mapper.BasUserSecurityMapper;
import com.weiyuwqj.server.mapper.BusAccountBankMapper;
import com.weiyuwqj.server.mapper.BusAccountMapper;
import com.weiyuwqj.server.mapper.BusGuaranteeSecurityMapper;
import com.weiyuwqj.server.mapper.BusIncomeStatMapper;
import com.weiyuwqj.server.mapper.BusUserIntegralMapper;
import com.weiyuwqj.server.mapper.BusUserStatMapper;
import com.weiyuwqj.server.mapper.SysAppSettingsMapper;
import com.weiyuwqj.server.mapper.SysLogMapper;
//import com.weiyuwqj.server.pay.MemberApi;
//import com.weiyuwqj.server.pay.PhoneApi;
import com.weiyuwqj.server.service.base.BaseServiceImpl;
import com.weiyuwqj.server.service.sys.module.ConfigTicketModule;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yandq on 15/10/11.
 */
@Service("userService")
public class BasUserServiceImpl extends BaseServiceImpl<BasUser> implements BasUserService {

    @Autowired
    private BasUserMapper basUserMapper;
    @Autowired
    private BasUserSecurityMapper userSecurityMapper;
    @Autowired
    private BusAccountMapper accountMapper;
    @Autowired
    private BusAccountBankMapper accountBankMapper;
    @Autowired
    private BusIncomeStatMapper incomeStatMapper;
    @Autowired
    private BasUserInfoMapper userInfoMapper;
    @Autowired
    private BusUserStatMapper userStatMapper;
    @Autowired
    private BasUserInviteMapper userInviteMapper;
    @Autowired
    private ConfigTicketModule ticketModule;
    @Autowired
    private BasExperiencedGoldMapper experiencedGoldMapper;
    @Autowired
    private BusUserIntegralMapper userIntegralMapper;
    @Autowired
    private SysLogMapper logMapper;
    @Autowired
    private SysAppSettingsMapper appSettingsMapper;
    @Autowired
    private BusGuaranteeSecurityMapper guaranteeSecurityMapper;
    @Autowired
    private BasCouponMapper couponMapper;
    @Autowired
    private BasTicketMapper ticketMapper;
//    @Autowired
//    private PhoneApi phoneApi;
//    @Autowired
//    private MemberApi memberApi;


    /**
     * 注册
     * @param user    用户对象
     * @param invite  邀请码
     * @param info    用户信息对象
     * @return
     */
    @Override
    public Integer doRegister(BasUser user, String invite,BasUserInfo info) {
        //密码
        String password = "";
        try {
            password = MD5.toMD5(user.getPassword()+user.getSalt());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //插入用户列表
        user.setPassword(password);
        basUserMapper.doRegister(user);
        //修改用户名
        Integer userId = user.getId();
        basUserMapper.modifyUsername("wqj2016" + userId, userId);
        //插入用户安全信息表
        BasUserSecurity userSecurity = new BasUserSecurity();
        userSecurity.setUserId(userId);
        userSecurity.setPhoneStatus(OftenUserdNumber.ZERO);
        userSecurity.setEmailStatus(OftenUserdNumber.ZERO);
        userSecurity.setRealnameStatus(OftenUserdNumber.ZERO);
        userSecurityMapper.insert(userSecurity);
        //插入用户资金表
        BusAccount account = new BusAccount();
        account.setUserId(userId);
        account.setFrozen(BigDecimal.ZERO);
        account.setWait(BigDecimal.ZERO);
        account.setRepay(BigDecimal.ZERO);
        account.setTotal(BigDecimal.ZERO);
        account.setUsable(BigDecimal.ZERO);
        account.setCash(BigDecimal.ZERO);
        accountMapper.insert(account);
        //插入用户收益统计表
        BusIncomeStat incomeStat = new BusIncomeStat();
        incomeStat.setUserId(userId);
        incomeStat.setEarnedIncome(BigDecimal.ZERO);
        incomeStat.setTotalIncome(BigDecimal.ZERO);
        incomeStat.setWaitIncome(BigDecimal.ZERO);
        incomeStatMapper.insert(incomeStat);
        //插入用户信息表
        if(null == info){
            info=new BasUserInfo();
        }
        info.setUserId(userId);
        info.setInviteCode(RandomCodesUtils.createRandom(false,4)+ RadixHelper.num2ThirtyFourRadix(userId));
        info.setCustomerType(OftenUserdNumber.ZERO);
        info.setCashLimit(OftenUserdNumber.ZERO);
        userInfoMapper.insert(info);
        //插入用户表
        BusUserStat userStat = new BusUserStat();
        userStat.setUserId(userId);
        userStat.setRechargeAmount(BigDecimal.ZERO);
        userStat.setRechargeCount(OftenUserdNumber.ZERO);
        userStat.setCashAmount(BigDecimal.ZERO);
        userStat.setCashCount(OftenUserdNumber.ZERO);
        userStat.setCouponAmount(BigDecimal.ZERO);
        userStat.setInvestAmount(BigDecimal.ZERO);
        userStat.setInvestLaveAmount(BigDecimal.ZERO);
        userStat.setInvestCount(OftenUserdNumber.ZERO);
        userStat.setCouponCount(OftenUserdNumber.ZERO);
        userStatMapper.insert(userStat);
        //判断邀请人
        if (!StringUtils.isEmpty(invite)) {
            BasUserInvite basUserInvite = new BasUserInvite();
            basUserInvite.setInviteId(userId);
            BasUserInfo userInfo=userInfoMapper.getByInviteCode(invite);
            if(userInfo == null){
                throw new CrowdException("invite_code.not_exists");
            }
            basUserInvite.setUserId(userInfo.getUserId());
            basUserInvite.setBonusEndTime(DateUtils.addDays(new Date(), Constants.days));
            basUserInvite.setAddtime(new Date());
            userInviteMapper.insert(basUserInvite);
        }
        //注册添加积分表
        BusUserIntegral userIntegral=new BusUserIntegral();
        userIntegral.setTotal(OftenUserdNumber.ZERO);
        userIntegral.setUsable(OftenUserdNumber.ZERO);
        userIntegral.setUserId(userId);
        userIntegralMapper.insert(userIntegral);
        //注册卡券奖励
        if(user.getType() == 1 ){
            TicketParamEntity param = new TicketParamEntity();
            param.setUserId(userId);
            param.setNid(Constants.register_nid);
            param.setAddIp(IpUtils.get());
            ticketModule.addTicket(param);
        }
        //注册获取奖励
        BasExperiencedGold experiencedGold = new BasExperiencedGold();
        experiencedGold.setUserId(userId);
        experiencedGold.setAmount(new BigDecimal(2888));
        experiencedGold.setExpiredTime(DateUtils.setDayLast(DateUtils.addDays(new Date(), Constants.days)));
        experiencedGold.setGoldName("注册体验金");
        experiencedGold.setWay("register");
        experiencedGold.setRate(new BigDecimal(18));
        experiencedGold.setStatus(2);
        experiencedGold.setUsefulLife(3);
        experiencedGold.setInvestId(OftenUserdNumber.ZERO);
        experiencedGold.setAddtime(new Date());
        experiencedGoldMapper.insert(experiencedGold);
        //添加app系统设置
        SysAppSettings appSettings = new SysAppSettings();
        appSettings.setUserId(userId);
        appSettings.setWhetherAppPush(1);
        appSettings.setWhetherSiteMail(1);
        appSettings.setWhetherSms(1);
        appSettings.setWhetherAccountProtect(OftenUserdNumber.ZERO);
        appSettings.setWhetherPatternLock(OftenUserdNumber.ZERO);
        appSettings.setWhetherTouchIdLock(OftenUserdNumber.ZERO);
        appSettingsMapper.insert(appSettings);
        //插入日志
        AbstractLogCreater logCreater = new RegisterLogCreater();
        logCreater.crate(userId,user.getAddip());
        logCreater.setProperty();
        logCreater.getLog().setResult(1);
        logMapper.insert(logCreater.getLog());

        return userId;
    }

    /**
     * 判断用户登录用户名或手机号码，密码是否正确
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public BasUser getUserByUsernameAndPassword(String username, String password) {
        BasUser user = basUserMapper.getUserByUsername(username);
        if (user != null) {
            String salt = user.getSalt();
            String realPassword = null;
            try {
                realPassword = MD5.toMD5(password + salt);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (!realPassword.equals(user.getPassword())) {
                //throw new CrowdException("user.login.password.password_not_correct");
                return null;
            }
        } else {
            user = basUserMapper.getUserByMobile(username);
            if(null==user){
                return null;
            }
            String salt = user.getSalt();
            String realPassword = null;
            try {
                realPassword = MD5.toMD5(password + salt);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (!realPassword.equals(user.getPassword())) {
                //throw new CrowdException("user.login.password.password_not_correct");
                return null;
            }
        }
        return user;
    }

    //根据用户名修改密码
    @Override
    public Integer modifyPassword(@Param("mobile") String mobile, @Param("newPassword") String newPassword) {
        return basUserMapper.modifyPassword(mobile, newPassword);
    }

    @Override
    public UserVo getUserByMobile(String mobile) {
        return basUserMapper.getUserByMobile(mobile);
    }

//    //修改手机号码
//    @Override
//    public Integer modifyMobile(String mobile, Integer id) {
//        Integer integer = basUserMapper.modifyMobile(mobile, id);// 修改手机号
//        BasUser user = basUserMapper.selectByPrimaryKey(id); // 用户信息
//        HfUserPlatformAccount userPlatformAccount = new HfUserPlatformAccount(); // 用户平台对象
//        userPlatformAccount.setOrder_no(com.weiyuwqj.api.util.StringUtils.getOrderNo()); // 订单号
//        userPlatformAccount.setPlatcust(user.getPlatformId()); // 平台编号
//        userPlatformAccount.setMobile(mobile); // 手机号
//        HfResultBean resultBean = memberApi.doUpdatePlatformAccount(userPlatformAccount);
//        return integer; // 修改客户信息请求
//    }


    @Override
    public Integer mobilePasswordByMobile(@Param("password") String password, @Param("mobile") String mobile) {
        return basUserMapper.mobilePasswordByMobile(password, mobile);
    }

    /**
     * 修改用户平台编号
     * @param platformId 用户平台
     * @param userId 用户ID
     * @return 修改返回行
     */
    @Override
    public Integer mobilePlatformId(String platformId, Integer userId) {
        return basUserMapper.mobilePlatformId(platformId, userId);
    }


//
//    @Override
//    public Map<String, Object> getCouponByUserName(Map<String, Object> map) {
//        return basUserMapper.getCouponByUserName(map);
//    }
//
//    @Override
//    public List<Map<String, Object>> excelList(Map<String, Object> map) {
//        return basUserMapper.getUsers(map);
//    }
//
//    //后台统计用户资金
//    @Override
//    public List<Map> getUserAmountCount(Paginator paginator, Map map) {
//        PageHelper.startPage(paginator.getPageNum(),paginator.getPageSize());
//        return basUserMapper.getUserAmountCount(map);
//    }
//
//    //后台统计用户资金导出
//    @Override
//    public List<Map> getUserAmountCount(Map map) {
//        return basUserMapper.getUserAmountCount(map);
//    }
//
//    @Override
//    public BasUser getUserByUsername(String username) {
//        return basUserMapper.getUserByUsername(username);
//    }
//
//    @Override
//    public BasUser getOneByUserIdAndPayPassword(Map map) {
//        return basUserMapper.getOneByUserIdAndPayPassword(map);
//    }

    //后台用户列表
    @Override
    public PageList getList(Paginator p, Map map) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<UserVo> list = basUserMapper.getList(map);
        for(UserVo userVo:list){
            Map param=new HashMap();
            param.put("status",1);
            param.put("userId",userVo.getId());
            BusAccountBank bank=accountBankMapper.getOneByUserIdAndStatus(param);
            if(bank !=null){
                userVo.setBankStatus(1);
            }else {
                userVo.setBankStatus(0);
            }
        }
        return new PageList(list);
    }


    //后台首页昨日今日注册数量
    @Override
    public Map countUserByTime() {
        return basUserMapper.countUserByTime();
    }

    @Override
    public BasUser getUserByUsername(String username) {
        return basUserMapper.getUserByUsername(username);
    }

//    //根据userid获取基本信息
//    @Override
//    public BasUserInfoVo getUserInfoById(Integer userId) {
//        BasUserInfoVo basUserInfoVo = basUserMapper.getUserInfoById(userId);
//        List<BusAccountBankVo> accountBank = accountBankMapper.getBankByUserId(userId);
//        basUserInfoVo.setAccountBankList(accountBank);
//        String area =phoneApi.getAddressByMobile(basUserInfoVo.getMobile());
//        basUserInfoVo.setArea(area);
//        Map map = new HashMap();
//        map.put("userId",userId);
//        map.put("status",2);
//        Integer couponCount= couponMapper.statCouponCount(map);
//        Integer ticketCount = ticketMapper.statTicketCount(map);
//        basUserInfoVo.setUsableCouponCount(couponCount);
//        basUserInfoVo.setUsableTicketCount(ticketCount);
//        return basUserInfoVo;
//    }

    //后台首页每天登陆人数统计
    @Override
    public Integer countUserLoginNum() {
        return basUserMapper.countUserLoginNum();

    }

    @Override
    public List<UserVo> getList(Map map) {
        return basUserMapper.getList(map);
    }

    @Override
    public List<Map> statUser(Map map) {
        return basUserMapper.statUser(map);
    }

    //后台用户投资统计列表
    @Override
    public List<UserInvestVo> listUserInvest(Map map) {
        List<UserInvestVo> list = basUserMapper.listUserInvest(map);
        return list;
    }

    @Override
    public List listByUserName(List userNameList) {
        List userList = basUserMapper.listByUserName(userNameList);
        return userList;
    }

    @Override
    public List listByInviteUser(List inviteUserNameList) {

        List<UserInvestVo> userList = basUserMapper.listByInviteUser(inviteUserNameList);
        return userList;
    }

    @Override
    public List<UserVo> listUser(Map map) {
        return basUserMapper.listUser(map);
    }

    @Override
    public BasUser getUserByThirdpart(Map map) {
        return basUserMapper.getUserByThirdpart(map);
    }


    @Override
    public GuaranteeSecurityAndBankVo getGuaranteeByUserId(Integer userId) {
        return guaranteeSecurityMapper.getOneByUserId(userId);
    }

//    /**
//     * 公司绑卡
//     * @param userId      用户id
//     * @param preMobile   预留手机号码
//     * @param orgNo       组织机构代码
//     * @param acctName    账户名称
//     * @param acctNo      账号
//     * @param openBranch  开户银行（精确到分行）
//     * @return
//     */
//    @Override
//    public void companyBank(Integer userId, String preMobile, String orgNo, String acctName,
//                            String acctNo, String openBranch,Integer type) {
//        HfUserBindCard userBindCard = new HfUserBindCard();
//        //根据userId查询用户信息
//        BasUser user = basUserMapper.selectByPrimaryKey(userId);
//        String orderNo = com.weiyuwqj.api.util.StringUtils.getOrderNo();
//        userBindCard.setOrder_no(orderNo);
//        userBindCard.setPlatcust(user.getPlatformId());
//        userBindCard.setAcct_no(acctNo);
//        userBindCard.setCard_type("1");
//        userBindCard.setType(type+"");
//        userBindCard.setPre_mobile(preMobile);
//        userBindCard.setOrg_no(orgNo);
//        userBindCard.setAcct_name(acctName);
//        userBindCard.setOpen_branch(openBranch);
////        userBindCard.setRemark("");
//        userBindCard.setPay_code(PayConstants.PAYCODE_LIANLIAN.toString());    //支付通道
//        userBindCard.setNotify_url(PayConstants.SERVER_REQUEST_URL.toString()+"/callback/notice/bindCard");  //请求回调地址
//        //请求恒丰
//        HfResultBean result = memberApi.doMemberCard(userBindCard);
//
//        BusAccountBank accountBank = new BusAccountBank();
//        accountBank.setAddtime(new Date());
//        accountBank.setBankName(openBranch);
//        accountBank.setCardNo(acctNo);
//        accountBank.setMobile(preMobile);
//        accountBank.setStatus(0);
//        accountBank.setType(type);
//        accountBank.setUserId(userId);
//        accountBankMapper.insert(accountBank);
//    }

    /**
     * 根据平台客户号查询信息
     * @param platformId
     * @return
     */
    @Override
    public BasUser getUserByPlatformId(String platformId) {
        return basUserMapper.getUserByPlatformId(platformId);
    }

    @Override
    public List<UserVo> getAssetList(Integer assetId) {
        List<UserVo> list = basUserMapper.getAssetList(assetId);
        for(int i =0;i<list.size();i++){
            BasUser user = list.get(i);
            BasUserSecurity security = userSecurityMapper.getOneByUserId(user.getId());
            if(security.getRealnameStatus()==0){
                list.remove(user);
                i--;
                continue;
            }
            BusAccountBank busAccountBank=accountBankMapper.getOneByUserId(user.getId());
            if(null == busAccountBank){
                list.remove(user);
                i--;
                continue;
            }
        }
        return list;
    }

	/**
	 * 获取企业投资用户
	 *
	 * @param balance 项目余额
	 * @return 企业投资用户列表
	 */
	@Override
	public List<BasUser> getEnterpriesUser(String balance) {
		Map<String, Object> param = new HashMap<>();
		param.put("type", 4); // 投资企业用户
		param.put("balance", balance); // 标余额
		return basUserMapper.getEnterpriesByParam(param);
	}
}
